package com.yunshangwoniu.core.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtils
{
	public static String getCookieValue(HttpServletRequest request, String cookieName, String defaultValue)
	{
		Cookie[] cookies = request.getCookies();
		if (cookies == null)
		{
			return (defaultValue);
		}
		for (int i = 0; i < cookies.length; i++)
		{
			Cookie cookie = cookies[i];
			if (cookieName.equals(cookie.getName()))
			{
				String d = null;
				try
				{
					d = URLDecoder.decode(cookie.getValue(), "utf-8");
				}
				catch (UnsupportedEncodingException e)
				{
					e.printStackTrace();
				}
			
				return d;
			}
		}
		return (defaultValue);
	}
	
	public static void createCookie(HttpServletRequest request, HttpServletResponse response,String coiokieName, String cookieValue, int maxAgeBySecond,String domain)
	{
		Cookie cookie = new Cookie(coiokieName, cookieValue);
        cookie.setMaxAge(maxAgeBySecond);
        cookie.setPath("/");
        cookie.setDomain(domain);
        response.addCookie(cookie);
	}
}
